<?php

namespace App\Admin\Extensions;

use Encore\Admin\Admin;

class CancelMember
{
    protected $id;
    protected $url;

    public function __construct($id)
    {
        $this->id = $id;
        $this->url = admin_url('users/cancel-member');
    }

    /**
     * @return string
     */
    public function getToken()
    {
        return csrf_token();
    }

    public function getUrl($id)
    {
        return admin_url('members/' . $id . '/cancel');
    }

    protected function script()
    {
        return <<<SCRIPT

$('.grid-cancel-member-row').on('click', function () {

    // Your code.
    var id = $(this).data('id');
    swal({
        title: "确定取消会员资格吗？",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确定",
        showLoaderOnConfirm: true,
        cancelButtonText: "取消",
        preConfirm: function() {
            return new Promise(function(resolve) {
                $.ajax({
                    method: 'post',
                    url: '{$this->getUrl("' + id + '")}',
                    data: {
                        _method:'patch',
                        _token:'{$this->getToken()}'
                    },
                    success: function (data) {
                        $.pjax.reload('#pjax-container');
                        resolve(data);
                    }
                });
            });
        }
    }).then(function(result) {
        console.log(result)
        var data = result.value;
        if (typeof data === 'object') {
            if (data.status) {
                swal(data.message, '', 'success');
            } else {
                swal(data.message, '', 'error');
            }
        }
    });
});

SCRIPT;
    }

    protected function render()
    {
        Admin::script($this->script());

        return "<a title='取消会员资格' class='grid-cancel-member-row' data-id='{$this->id}'><i class='fa fa-paper-plane'></i></a>";
    }

    public function __toString()
    {
        return $this->render();
    }
}
